<template>
  <div>
    <div style="display: flex; justify-content: flex-end">
      <el-form :model="queryParams" label-position="right" size="small" class="filter-form-inline">
        <el-row :gutter="40" style="margin-left: 0px; margin-right: 0px">
          <el-form-item label="状态" style="width:300px;margin-right:20px;">
            <el-select v-model="queryParams.devStatus" clearable placeholder="请选择产品" @change="handlChangeDevStatus">
              <el-option
                v-for="item in devStatusList"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <filter-popover
              right="20px"
              :form-list="formList"
              @onConfirm="filterDataConfirm"
              @onReset="filterReset"
            />
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <table-view
      :data="tableData"
      header-cell-class-name="table-header"
      size="medium"
      border
      :cell-style="cellStyle"
      @row-click="aloneClick"
    >
      <el-table-column
        prop="terminalName"
        label="终端名称"
        :min-width="160"
        fixed="left"
        header-align="center"
        :show-overflow-tooltip="true"
      />

      <el-table-column label="终端所在地区" align="center" :min-width="160" fixed="left" :show-overflow-tooltip="true">
        <template #default="{row}">
          {{ row.provinceName }}/{{ row.cityName }}/{{ row.areaName }}
        </template>
      </el-table-column>

      <el-table-column
        prop="productPopularName"
        label="产品名称"
        :min-width="160"
        fixed="left"
        header-align="center"
        :show-overflow-tooltip="true"
      />

      <el-table-column prop="approvalNumber" label="批准文号" :min-width="160" header-align="center" :show-overflow-tooltip="true" />

      <el-table-column prop="packSpecs" label="包装规格" align="center" :min-width="140" :show-overflow-tooltip="true" />

      <el-table-column prop="terminalPrice" label="终端价(元)" align="center" width="120" :show-overflow-tooltip="true">
        <template #default="{row}">
          <div style="text-align: right">
            {{ isInteger(row.terminalPrice) }}
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="tradePrice" label="交易价(元)" align="center" width="140" :show-overflow-tooltip="true">
        <template #default="{row}">
          <div style="text-align: right">
            {{ isInteger(row.tradePrice) }}
          </div>
        </template>
      </el-table-column>

      <el-table-column label="配送商" align="center" :min-width="160" :show-overflow-tooltip="true">
        <template #default="{row}">
          <distributors-view
            v-if="row.distributeContractDetails && row.distributeContractDetails.length"
            :datas="row.distributeContractDetails"
            :unit="row.productInfoDetail?.sellUnit"
          />
        </template>
      </el-table-column>

      <el-table-column
        prop="devEarnestMoney"
        label="开发保证金(元)"
        width="140"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template #default="{row}">
          <div style="text-align: right">
            {{ isInteger(row.devEarnestMoney) }}
          </div>
        </template>
      </el-table-column>

      <el-table-column label="开发期限截止" align="center" width="120" :show-overflow-tooltip="true">
        <template #default="{row}">
          {{ dateFormat("yyyy-mm-dd",row.expireTime) }}
        </template>
      </el-table-column>

      <el-table-column label="注册日期" align="center" fixed="right" width="120" :show-overflow-tooltip="true">
        <template #default="{row}">
          {{ dateFormat("yyyy-mm-dd",row.agentRegisterTime) }}
        </template>
      </el-table-column>

      <el-table-column prop="address" label="状态" align="center" fixed="right" width="120" :show-overflow-tooltip="true">
        <template #default="{row}">
          <div v-if="row.flowStatus!=='DOING'" style="line-height: 20px">{{ getLabel('devStatus', row.devStatus) }}</div>
          <div
            v-if="row.flowStatus ==='DOING'"
            style="line-height: 20px"
          >{{ getLabel('approval_result',row.flowStatus) }}
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" fixed="right" width="200" align="center">
        <template #default="{row}">
          <el-button
            v-if="row.flowStatus ==='REFUSE' || row.flowStatus ==='REPEAL'
              || row.devStatus === '-2'||row.flowStatus ==='REJECT'"
            type="text"
            @click="handlDele(row.id,1)"
          >删除
          </el-button>

          <template v-if="row.devStatus ==='2' || row.devStatus ==='4' ">
            <el-button type="text" @click="handlFailure(row,1)">开发失败</el-button>
          </template>
        </template>
      </el-table-column>
    </table-view>
    <Pagination
      v-model:page="queryParams.page"
      v-model:limit="queryParams.pageSize"
      style="display: flex; justify-content: flex-end"
      :total="total"
      @pagination="handlList"
    />

    <!--设置配送信息-->
    <setiDelivery ref="setiDeliveryDialog" />
    <!-- 开发中终端详情 -->
    <detail-drawer ref="detailDrawer" custom-title :size-width="1000">
      <template #title>
        <div style="display: flex;justify-content: space-between;align-items: center">
          <div style="width: 40%">
            <span style="padding-right: 15px">{{ productData?.terminalName }} </span>
            <el-tag v-if="productData.flowStatus!=='DOING'" :type="statusType" size="small">
              {{ getLabel('devStatus', productData.devStatus) }}
            </el-tag>
            <el-tag v-if="productData.flowStatus ==='DOING'" :type="statusType" size="small">
              {{ getLabel('approval_result',productData.flowStatus) }}
            </el-tag>
          </div>
          <div style="width: 60%;text-align: right">
            <template
              v-if="productData.flowStatus ==='REFUSE' || productData.devStatus === '-2' ||
                productData.flowStatus ==='REPEAL' || productData.flowStatus ==='REJECT'"
            >
              <el-button type="primary" size="mini" @click="handlDele(productData.id,2)">删除</el-button>
            </template>

            <template v-if="productData.devStatus ==='2' || productData.devStatus ==='4' ">

              <el-button type="primary" size="mini" @click="handlFailure(productData,2)">开发失败</el-button>
            </template>
          </div>
        </div>

      </template>
      <template #contents>
        <div class="drawer-content">
          <div class="history-list">
            <product-detail ref="productDetailDrawer" :product-id="productData.id" />
          </div>
        </div>
      </template>
    </detail-drawer>
  </div>
</template>

<script>
import {defineAsyncComponent, getCurrentInstance, inject, onMounted, reactive, toRefs} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {crmStore} from '@CRM/store'

export default {
  name: 'DevelopmentTerminal',
  components: {
    setiDelivery: defineAsyncComponent(() => import('@CRM/views/marketing/customer/terminal/modules/setiDelivery.vue')),
    productDetail: defineAsyncComponent(() => import('@CRM/views/marketing/customer/terminal/modules/productDetail.vue')),
  },
  setup(props, context) {
    const api = inject('api')
    const router = useRouter()
    const route = useRoute()
    const currentInstance = getCurrentInstance()
    var data = reactive({
      tableData: [],
      formTerminal: null,
      queryParams: {
        agentId: Number(route.query.id),
        pageSize: 20,
        page: 1,
        keyWord: '',
        productId: '',
        devStatus: '',
        registerStartTime: null, // 必须
        registerEndTime: null, //
        expireTimeStart: null,
        expireTimeEnd: null,
        provinceCode: '',
        cityCode: '',
        areaCode: '',
      },
      total: 0,
      detailDrawer: null,
      setiDeliveryDialog: null,
      productDetailDrawer: null,
      productData: null,
      productList: [],
      devStatusList: crmStore.getters['dictionary/getDictionary']['devStatus'].filter(a => a.value !== '5'),
      formList: [
        {
          key: 'productId',
          label: '产品信息',
          form_type: 'select',
          value: '',
          is_search: false,
          options: [],
          setting: {
            label: 'productPopularName',
            value: 'id',
          },
        },
        {
          key: 'keyWord',
          label: '关键字',
          form_type: 'text',
          value: '',
          is_search: false,
          options: [],
        },
        {
          key: 'date_range1',
          label: '注册日期',
          form_type: 'daterange',
          value: [],
          is_search: false,
          options: [],
        },
        {
          key: 'date_range2',
          label: '开发截止日期',
          form_type: 'daterange',
          value: [],
          is_search: false,
          options: [],
        },
        {
          key: 'area',
          label: '终端所在地区',
          form_type: 'cascader',
          value: [],
          is_search: false,
          multiple: false,
          checkStrictly: false,
          options: [],
        },

      ]
    })

    const handlAdd = () => {
      data.formTerminal.open()
    }

    // 确定搜所
    const filterDataConfirm = (val) => {
      data.queryParams.productId = val.productId
      data.queryParams.keyWord = val.keyWord
      data.queryParams.registerStartTime = val.date_range1[0]
      data.queryParams.registerStartTime = val.date_range1[1]
      data.queryParams.expireTimeStart = val.date_range2[0]
      data.queryParams.expireTimeEnd = val.date_range2[1]
      data.queryParams.provinceCode = val.area[0]
      data.queryParams.cityCode = val.area[1]
      data.queryParams.areaCode = val.area[2]
      data.queryParams.page = 1
      handlList()
    }

    // 取消
    const filterReset = () => {
      data.queryParams = {
        agentId: Number(route.query.id),
        pageSize: 20,
        page: 1,
        keyWord: '',
        productId: '',
        devStatus: '',
        registerStartTime: null, // 必须
        registerEndTime: null, //
        expireTimeStart: null,
        expireTimeEnd: null,
        provinceCode: '',
        cityCode: '',
        areaCode: '',
      }
      handlList()
    }

    // 获取产品下拉
    const handlProductData = async() => {
      const a = {
        id: Number(route.query.id),
        type: 1,
        productPopularName: ''
      }
      const res = await api.terminal.TERMINAL_PRODUCTIDSS(a)
      if (res.code === 0) {
        data.productList = res.data.agentProduct
        data.formList[0].options = res.data.agentProduct
      }
    }

    // 产品事件
    const handlChangeProduct = (val) => {
      if (val) {
        data.queryParams.productId = val
      } else {
        data.queryParams.productId = 0
      }
      data.queryParams.page = 1
      handlList()
    }

    // 获取列表
    const handlList = () => {
      const a = JSON.parse(JSON.stringify(data.queryParams))
      a.productId = Number(a.productId)
      api.channelAgent.PARTTIMEBIGBAG_TERMINAL_CREATE(a).then(res => {
        if (res.code === 0) {
          data.tableData = res.data.list || []
          data.total = res.data.total
        }
      })
    }

    // 设置配送信息
    const handlSet = (val) => {
      data.setiDeliveryDialog.open(val)
    }

    const aloneClick = (row, column, event) => {
      if (column.label === '操作' || column.label === '查看文件') return
      data.detailDrawer.open()
      data.productData = row
      data.productId = row.id
    }

    const cellStyle = () => {
      return 'cursor:pointer;'
    }

    const handlFailure = (row, num) => {
      currentInstance.proxy
        .alertBox({
          message: '确认更改该终端产品状态为开发失败？',
        })
        .then(() => {
          api.terminal.TERMINAL_FAILURE(row.id).then((res) => {
            if (res.code) {
              currentInstance.proxy.customMessage({ type: 'error', message: res.msg })
            } else {
              if (num === 2) {
                data.productDetailDrawer.handlDetail()
              } else {
                handlList()
              }
            }
          })
        })
        .catch((err) => {
          console.log(err)
        })
    }

    // 删除
    const handlDele = (id, num) => {
      currentInstance.proxy
        .alertBox({
          message: '删除数据后不可恢复,确定删除？',
        })
        .then(() => {
          api.terminal.REGISTERED_DELETE(id).then((res) => {
            if (res.code === 0) {
              if (num === 2) {
                data.detailDrawer.close()
              } else {
                handlList()
              }
            } else {
              currentInstance.proxy.customMessage({ type: 'error', message: res.msg })
            }
          })
        })
        .catch((err) => {
          console.log(err)
        })
    }

    onMounted(_ => {
      handlList()
      handlProductData()
    })
    return {
      ...toRefs(data),
      handlAdd,
      aloneClick,
      cellStyle,
      handlList,
      handlSet,
      handlFailure,
      handlDele,
      handlChangeProduct,
      handlProductData,
      filterReset,
      filterDataConfirm
    }
  }
}

</script>

<style scoped>
  /* @import url(); 引入css类 */
</style>
